package com.bdqn.t350.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

//@WebFilter(filterName = "SessionFilter", urlPatterns = "/*")
public class SessionFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        //获取当前访问的url路径
        String servletPath = httpServletRequest.getServletPath();
        System.out.println("servletPath:" + servletPath);
        if (servletPath.equals("/error.jsp")
                || servletPath.equals("/login.jsp")
                || servletPath.equals("/LoginServlet")
                || servletPath.startsWith("/js/")
                || servletPath.startsWith("/ImageServlet")
                || servletPath.startsWith("/static")) {
            //去你该去的地方
            chain.doFilter(req, resp);
        } else {
            HttpSession session = httpServletRequest.getSession();
            if (session == null || session.getAttribute("name") == null) {
                resp.setContentType("text/html;charset=UTF-8");
                PrintWriter out = resp.getWriter();
                out.print("<script>alert('过滤器拦截是否登录');location.href='error.jsp'</script>");
            } else {
                //去你该去的地方
                chain.doFilter(req, resp);
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }
}
